const dataList = document.getElementById('data-list');

// 轮播图功能
let currentSlide = 0;
const slides = document.querySelectorAll('.carousel-slide');
const indicators = document.querySelectorAll('.indicator');

function showSlide(index) {
    // 隐藏所有幻灯片
    slides.forEach(slide => {
        slide.style.display = 'none';
    });
    // 显示指定幻灯片
    slides[index].style.display = 'block';

    // 更新指示器
    indicators.forEach(indicator => {
        indicator.classList.remove('active');
    });
    indicators[index].classList.add('active');

    currentSlide = index;
}

function nextSlide() {
    currentSlide = (currentSlide + 1) % slides.length;
    showSlide(currentSlide);
}

// 自动播放
let slideInterval = setInterval(nextSlide, 3000);

// 指示器点击事件
indicators.forEach((indicator, index) => {
    indicator.addEventListener('click', () => {
        clearInterval(slideInterval);
        showSlide(index);
        slideInterval = setInterval(nextSlide, 3000);
    });
});

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 初始化显示第一张幻灯片
    showSlide(currentSlide);
    
    // 菜单功能初始化
    const menuItems = document.querySelectorAll('.menu-item');
    const submenuItems = document.querySelectorAll('.submenu-item');
    let activeSubmenu = null;
    
    // 菜单点击事件
    menuItems.forEach(item => {
        item.addEventListener('click', function (e) {
            // 移除所有菜单项的激活状态
            menuItems.forEach(i => i.classList.remove('active'));

            // 添加当前点击项的激活状态
            this.classList.add('active');

            // 显示 submenu（如果存在）
            const submenu = this.querySelector('.submenu');
            if (submenu) {
                // 隐藏之前激活的 submenu
                if (activeSubmenu && activeSubmenu !== submenu) {
                    activeSubmenu.style.display = 'none';
                }

                // 显示当前 submenu
                submenu.style.display = 'flex';
                activeSubmenu = submenu;
            } else {
                // 如果点击的菜单项没有 submenu，隐藏所有 submenu
                document.querySelectorAll('.submenu').forEach(sub => {
                    sub.style.display = 'none';
                });
                activeSubmenu = null;
            }
        });

        // 鼠标移入事件
        item.addEventListener('mouseenter', function () {
            // 隐藏所有已激活的 submenu
            if (activeSubmenu) {
                activeSubmenu.style.display = 'none';
                activeSubmenu = null;
            }

            // 显示当前菜单项的 submenu（如果存在）
            const submenu = this.querySelector('.submenu');
            if (submenu) {
                submenu.style.display = 'flex';
                activeSubmenu = submenu;
            }
        });

        // 鼠标移出事件
        item.addEventListener('mouseleave', function (e) {
            // 检查鼠标是否移向 submenu
            const submenu = this.querySelector('.submenu');
            if (submenu && activeSubmenu === submenu) {
                // 使用 setTimeout 来处理鼠标移出到 submenu 的情况
                setTimeout(() => {
                    if (!submenu.matches(':hover')) {
                        submenu.style.display = 'none';
                        if (activeSubmenu === submenu) {
                            activeSubmenu = null;
                        }
                    }
                }, 100);
            }
        });
    });

    // 二级菜单点击事件
    submenuItems.forEach(item => {
        item.addEventListener('click', function (e) {
            e.stopPropagation(); // 阻止事件冒泡

            // 移除所有菜单项的激活状态
            menuItems.forEach(i => i.classList.remove('active'));

            // 添加父级菜单项的激活状态
            this.closest('.menu-item').classList.add('active');
            
            // 页面跳转逻辑
            const submenuType = this.getAttribute('data-submenu');
            let targetUrl = '';
            
            // 根据submenu类型设置跳转URL
            if (submenuType === 'status1') {
                targetUrl = '../work-status/index.html?type=exhibition';
            } else if (submenuType === 'statu2') {
                targetUrl = '../work-status/index.html?type=inquiry';
            } else if (submenuType === 'service4') {
                targetUrl = '../public-service/index.html?type=exhibition';
            } else if (submenuType === 'service5') {
                targetUrl = '../public-service/index.html?type=inquiry';
            } else if (submenuType === 'service1') {
                targetUrl = '../public-service/index.html?type=reservation';
            } else if (submenuType === 'service2') {
                targetUrl = '../public-service/index.html?type=message';
            } else if (submenuType === 'service3') {
                targetUrl = '../public-service/index.html?type=donation';
            } else if (submenuType === 'overview1') {
                targetUrl = '../archival-collections/index.html?type=inquiry';
            } else if (submenuType === 'overview2') {
                targetUrl = '../archival-collections/index.html?type=exhibition';
            } else if (submenuType === 'culture1') {
                targetUrl = '../chronicle-culture/index.html?type=exhibition';
            } else if (submenuType === 'culture2') {
                targetUrl = '../chronicle-culture/index.html?type=inquiry';
            } else if (submenuType === 'culture3') {
                targetUrl = '../chronicle-culture/index.html?type=culture';
            }
            
            // 跳转到对应页面
            if (targetUrl) {
                window.location.href = targetUrl;
            }
        });
    });
    
    // 为快捷入口添加点击效果
    const accessItems = document.querySelectorAll('.access-item');
    accessItems.forEach(item => {
        item.addEventListener('click', function() {
            alert('您点击了：' + this.querySelector('p').textContent);
        });
    });
    
    // 为平台链接添加点击效果
    const platformItems = document.querySelectorAll('.platform-item');
    platformItems.forEach(item => {
        item.addEventListener('click', function() {
            alert('您点击了：' + this.querySelector('img').alt);
        });
    });
    
    // 为编研成果添加点击效果
    const caseItems = document.querySelectorAll('.case-item');
    caseItems.forEach(item => {
        item.addEventListener('click', function() {
            alert('您点击了：' + this.querySelector('.case-title').textContent);
        });
    });
    
    // 为网上展厅添加点击效果
    const exhibitionItems = document.querySelectorAll('.exhibition-item');
    exhibitionItems.forEach(item => {
        item.addEventListener('click', function() {
            alert('您点击了：' + this.querySelector('.exhibition-title').textContent);
        });
    });
    
    // 为工作动态、法规标准、通知公告等列表项添加点击效果
    const listItems = document.querySelectorAll('.dynamic-item, .regulations-item, .notices-item');
    listItems.forEach(item => {
        item.addEventListener('click', function() {
            alert('您点击了：' + this.querySelector('.title').textContent);
        });
    });
    
    // 为主题教育横幅添加点击效果
    const themeEducation = document.querySelector('.theme-education');
    if (themeEducation) {
        themeEducation.addEventListener('click', function() {
            alert('学习贯彻习近平新时代中国特色社会主义思想主题教育');
        });
    }
    
    // 为section-title-pre添加tab切换功能
    const tabItems = document.querySelectorAll('.section-title-pre');
    const tabContents = document.querySelectorAll('.tab-content');
    
    tabItems.forEach(item => {
        item.addEventListener('click', function() {
            // 移除所有tab的active类
            tabItems.forEach(tab => tab.classList.remove('active'));
            // 为当前点击的tab添加active类
            this.classList.add('active');
            
            // 根据tab切换内容
            const tabText = this.textContent;
            if (tabText === '单位概况') {
                // 显示单位概况内容，隐藏工作动态内容
                document.getElementById('overview-content').style.display = 'block';
                document.getElementById('work-dynamic-content').style.display = 'none';
            } else if (tabText === '工作动态') {
                // 显示工作动态内容，隐藏单位概况内容
                document.getElementById('overview-content').style.display = 'none';
                document.getElementById('work-dynamic-content').style.display = 'block';
            }
        });
    });
    
    // 默认激活第一个tab
    if (tabItems.length > 0) {
        tabItems[0].classList.add('active');
    }
    
    // 为工作动态列表项添加点击效果
    const dynamicItems = document.querySelectorAll('.dynamic-item');
    dynamicItems.forEach(item => {
        item.addEventListener('click', function() {
            alert('您点击了：' + this.querySelector('.title').textContent);
        });
    });
    
    // 为编研成果和志鉴案例添加tab切换功能
    const researchTabItems2 = document.querySelectorAll('.research-cases .section-title-pre');
    researchTabItems2.forEach(item => {
        item.addEventListener('click', function() {
            // 移除所有tab的active类
            researchTabItems2.forEach(tab => tab.classList.remove('active'));
            // 为当前点击的tab添加active类
            this.classList.add('active');
            
            // 根据tab切换内容
            const tabText = this.textContent;
            if (tabText === '编研成果') {
                document.getElementById('research-content').style.display = 'flex';
                document.getElementById('cases-content').style.display = 'none';
            } else if (tabText === '志鉴案例') {
                document.getElementById('research-content').style.display = 'none';
                document.getElementById('cases-content').style.display = 'flex';
            }
        });
    });
    
    // 默认激活编研成果tab
    if (researchTabItems2.length > 0) {
        researchTabItems2[0].classList.add('active');
    }
    
    // 为网上展厅和主题活动添加tab切换功能
    const exhibitionTabItems = document.querySelectorAll('.online-exhibition .section-title-pre');
    exhibitionTabItems.forEach(item => {
        item.addEventListener('click', function() {
            // 移除所有tab的active类
            exhibitionTabItems.forEach(tab => tab.classList.remove('active'));
            // 为当前点击的tab添加active类
            this.classList.add('active');
            
            // 根据tab切换内容
            const tabText = this.textContent;
            if (tabText === '特色展览') {
                document.getElementById('exhibition-content').style.display = 'block';
                document.getElementById('activities-content').style.display = 'none';
            } else if (tabText === '主题活动') {
                document.getElementById('exhibition-content').style.display = 'none';
                document.getElementById('activities-content').style.display = 'block';
            }
        });
    });
    
    // 默认激活特色展览tab
    if (exhibitionTabItems.length > 0) {
        exhibitionTabItems[0].classList.add('active');
    }
    
    // 为编研成果和网上展厅的项目添加点击效果
    const caseItems2 = document.querySelectorAll('.case-item');
    caseItems2.forEach(item => {
        item.addEventListener('click', function() {
            // 这里可以添加点击后的跳转逻辑
            console.log('Case item clicked:', this.querySelector('.case-title').textContent);
        });
    });

    const exhibitionItems2 = document.querySelectorAll('.exhibition-item');
    exhibitionItems2.forEach(item => {
        item.addEventListener('click', function() {
            // 这里可以添加点击后的跳转逻辑
            console.log('Exhibition item clicked:', this.querySelector('.exhibition-title').textContent);
        });
    });

    // 编研成果轮播图功能
    let researchSlideIndex = 0;
    const researchContainer = document.querySelector('#research-content .cases-container');
    const researchItems = document.querySelectorAll('#research-content .case-item');
    const researchLeftArrow = document.querySelector('.research-left-arrow');
    const researchRightArrow = document.querySelector('.research-right-arrow');
    const researchTotalItems = researchItems.length;
    const researchItemsPerView = 4;
    const researchMaxIndex = Math.max(0, researchTotalItems - researchItemsPerView);

    // 计算每个item的宽度（考虑到间距）
    function calculateItemWidth(items, perView, gap) {
        if (items.length === 0) return 0;
        // 移除之前设置的宽度，以便获取实际的容器宽度
        items.forEach(item => {
            item.style.width = 'auto';
        });
        
        const containerWidth = items[0].parentElement.clientWidth;
        return (containerWidth - (gap * (perView - 1))) / perView;
    }

    function updateResearchSlide() {
        // 每个item之间的间距为20px
        const itemWidth = calculateItemWidth(researchItems, researchItemsPerView, 20);
        
        // 设置每个item的固定宽度
        researchItems.forEach(item => {
            item.style.width = `${itemWidth}px`;
        });
        
        // 计算位移量，考虑到间距
        const translateX = -researchSlideIndex * (itemWidth + 20);
        researchContainer.style.transform = `translateX(${translateX}px)`;
    }

    researchLeftArrow.addEventListener('click', function() {
        researchSlideIndex = Math.max(0, researchSlideIndex - 1);
        updateResearchSlide();
    });

    researchRightArrow.addEventListener('click', function() {
        researchSlideIndex = Math.min(researchMaxIndex, researchSlideIndex + 1);
        updateResearchSlide();
    });

    // 志鉴案例轮播图功能
    let casesSlideIndex = 0;
    const casesContainer = document.querySelector('#cases-content .cases-container');
    const casesItems = document.querySelectorAll('#cases-content .case-item');
    const casesLeftArrow = document.querySelector('.cases-left-arrow');
    const casesRightArrow = document.querySelector('.cases-right-arrow');
    const casesTotalItems = casesItems.length;
    const casesItemsPerView = 4;
    const casesMaxIndex = Math.max(0, casesTotalItems - casesItemsPerView);

    function updateCasesSlide() {
        // 每个item之间的间距为20px
        const itemWidth = calculateItemWidth(casesItems, casesItemsPerView, 20);
        
        // 设置每个item的固定宽度
        casesItems.forEach(item => {
            item.style.width = `${itemWidth}px`;
        });
        
        // 计算位移量，考虑到间距
        const translateX = -casesSlideIndex * (itemWidth + 20);
        casesContainer.style.transform = `translateX(${translateX}px)`;
    }

    casesLeftArrow.addEventListener('click', function() {
        casesSlideIndex = Math.max(0, casesSlideIndex - 1);
        updateCasesSlide();
    });

    casesRightArrow.addEventListener('click', function() {
        casesSlideIndex = Math.min(casesMaxIndex, casesSlideIndex + 1);
        updateCasesSlide();
    });

    // 在窗口大小改变时重新计算轮播图
    window.addEventListener('resize', function() {
        updateResearchSlide();
        updateCasesSlide();
    });

    // 初始化轮播图
    updateResearchSlide();
    updateCasesSlide();

    // 在tab切换时重置轮播图索引
    const researchTabItems = document.querySelectorAll('.research-cases .section-title-pre');
    researchTabItems.forEach(item => {
        item.addEventListener('click', function() {
            if (this.textContent.trim() === '编研成果') {
                researchSlideIndex = 0;
                updateResearchSlide();
            } else if (this.textContent.trim() === '志鉴案例') {
                casesSlideIndex = 0;
                updateCasesSlide();
            }
        });
    });
});